<template>
  <el-dialog
    title="添加用户"
    :visible="dialogVisible"
    width="50%"
    @close="onDialogClose"
  >
    <el-form ref="Form" :model="ruleForm" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="ruleForm.email" />
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="ruleForm.mobile" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="$emit('input',false)">取 消</el-button>
      <el-button type="primary" @click="addUser">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addUser } from '@/api/user.js'

export default {
  model: {
    prop: 'dialogVisible'
  },
  props: {
    dialogVisible: {
      type: Boolean,
      required: true
    },
    tableData: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      ruleForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 7, message: '输入用户名为2-7位', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 2, max: 7, message: '输入密码为2-7位', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validateField: '/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/', message: '请输入正确格式', trigger: 'blur' }
        ]
      }
    }
  },

  created() {

  },

  methods: {
    // 关闭弹层
    onDialogClose() {
      this.$emit('input', false)
    },
    // 点击确认发送请求  添加用户
    async addUser() {
      await this.$refs.Form.validate()
      try {
        await addUser(this.ruleForm)
        this.$message.success('添加成功')
        this.onDialogClose()
        this.$emit('loadUser')
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style scoped lang='less'>

</style>
